"""
购物相关接口
"""

from db import db_handler
from interface import bank_interface
from lib import common


logger = common.get_logger("shop")


# 获取商品列表的接口
def get_goods_list_interface(goods_name):
    goods_list = db_handler.select_data(goods_name, is_user=False)

    if not goods_list:
        logger.error(f"商品恩建：{goods_name}丢失！")

    return goods_list


# 添加购物车接口
def add_shopping_cart_interface(logged_user, shopping_cart_data):

    # 拿到用户数据里的购物车数据
    user_data = db_handler.select_data(logged_user)
    shopping_cart_file = user_data["shopping_cart"]

    # 添加购物车
    for name in shopping_cart_data.keys():
        if name in shopping_cart_file:
            shopping_cart_file[name]["数量"] += shopping_cart_data.get(name).get("数量")
        else:
            shopping_cart_file[name] = shopping_cart_data.get(name)

    # 保存更新后的购物车数据
    db_handler.save_data(user_data)

    logger.info("购物车添加成功！")

    return True, "\n购物车添加成功！"


# 结算购物车接口
def settlement_shopping_cart_interface(logged_user, shopping_cart_data):

    # 计算结算的总金额
    total_price = 0
    for good_info in shopping_cart_data.values():
        price = good_info.get("price")
        num = good_info.get("数量")
        total_price += price * num

    flag, msg = bank_interface.pay_interface(logged_user, total_price)
    return flag, msg, total_price


# 查看购物车接口
def get_shopping_cart_interface(logged_user):

    # 拿到用户数据里的购物车数据
    user_data = db_handler.select_data(logged_user)
    shopping_cart_file = user_data.get("shopping_cart")

    return shopping_cart_file


# 删除购物车商品接口
def delete_shopping_cart_interface(logged_user, good_name):

    # 拿到用户数据里的购物车数据
    user_data = db_handler.select_data(logged_user)
    shopping_cart_file = user_data.get("shopping_cart")

    # 删除购物车商品
    if good_name in shopping_cart_file:
        del shopping_cart_file[good_name]

    logger.info(f"购物车商品{good_name}删除成功！")

    # 保存更新后的购物车数据
    db_handler.save_data(user_data)
